<template>
	<view>
		<u-navbar
			title="预订门票"
			:autoBack="true"
			placeholder
		>
		</u-navbar>
		<scroll-view :scroll-y="true" :style="{height: scrollViewHeight, backgroundColor: '#f5f5f5'}">
			<view style="padding: 32rpx;">
				<view style="background-color: #fff;">
					<view class="popup-title1">
						<u--image radius="8rpx" mode="aspectFill" :src="detail.image && detail.image.split(',')[0]" width="140rpx" height="140rpx"></u--image>
						<view style="height: 140rpx;display: flex;flex-direction: column;justify-content: space-between;margin-left: 32rpx;">
							<text style="font-size: 32rpx;color: #000;">{{detail.name}}</text>
							<text style="font-size: 28rpx;color: #666;">{{detail.tag_dictText}}</text>
						</view>
					</view>
					<view style="padding: 16rpx 32rpx;font-size: 32rpx;color: #333;display: flex;justify-content: space-between;align-items: center;">
						<text>游玩日期</text>
						<text style="padding-left: 32rpx;color: #000;font-size: 28rpx">{{detail.play_time}}({{detail.week_time}})</text>
					</view>
					<view style="padding: 16rpx 32rpx;font-size: 32rpx;color: #333;display: flex;justify-content: space-between;align-items: center;">
						<text>购买数量</text>
						<view>
							<u-number-box asyncChange @change="changeCount" integer disabledInput v-model="value" :max="detail.limitNum"></u-number-box>
						</view>
					</view>
					<view style="padding: 16rpx 32rpx;">
						<view class="buy-notice1" :style="{color: appColor, backgroundColor: appColor + '33'}">每单1张起购, 每单最多可买{{detail.limitNum}}张</view>
					</view>
					<view style="height: 16rpx;" />
				</view>
				<view style="height: 16rpx;" />
				<view style="background-color: #fff;">
					<view class="shop-order-info-3-item" @click="chooseCoupon">
						<text class="shop-order-info-3-item-l">优惠券</text>
						<text class="shop-order-info-3-item-r" style="color: #999;font-weight: normal;" v-if="!curCoupon.id">请选择<text class="iconfont icon-youjiantou"></text> </text>
						<text class="shop-order-info-3-item-r" style="color: #f40215;font-weight: normal;" v-else>-&yen;{{prices.couponPrice || 0}}</text>
					</view>
				</view>
				<view style="height: 16rpx;" />
				<view style="background-color: #fff;">
					<view style="padding: 16rpx 32rpx;font-size: 32rpx;color: #333;">
						<text>游客信息</text>
					</view>
					<view v-for="(item, index) in list" :key="index">
						<view style="padding: 16rpx 32rpx;" >
							<u--form
								labelWidth="80"
								labelPosition="left"
								:model="item"
								ref="form1"
							>
								<view v-if="list.length>1" style="font-size: 30rpx;color: #000;">游客{{index+1}}</view>
								<u-form-item
									label="姓名"
									borderBottom
								>
									<u--input
										v-model="item.userInfo.name"
										border="none"
										placeholder="游玩人姓名, 保持证件一致"
									></u--input>
								</u-form-item>
								<u-form-item
									label="身份证"
									:borderBottom="false"
								>
									<u--input
										v-model="item.userInfo.card"
										border="none"
										placeholder="输入身份证号"
										type="idcard"
									></u--input>
								</u-form-item>
							</u--form>
						</view>
						<view style="height: 16rpx;background-color: #f5f5f5;"></view>
					</view>
					<view style="padding: 16rpx 32rpx;" >
						<u--form
							labelWidth="80"
							labelPosition="left"
							:model="model"
							ref="form2"
						>
							<u-form-item
								label="手机号"
								:borderBottom="false"
							>
								<u--input
									v-model="model.userinfo.phone"
									border="none"
									placeholder="便于联系或接受预订信息"
								></u--input>
							</u-form-item>
						</u--form>
					</view>
				</view>
				<view style="height: 16rpx;" />
				<view style="background-color: #fff;">
					<view style="padding: 16rpx 32rpx;font-size: 32rpx;color: #333;">
						<JoyPay fontSize="32rpx" fontBold="normal" @changePay="changePay"/>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="good-detail-bootom">
			<view style="margin: 0 32rpx;height: 100%;width: calc(100vw - 64rpx);display: flex;align-items: center;justify-content: space-between;">
				<view class="good-detail-bootom-l1">
					<text :style="{color: appColor}">&yen;</text>
					<text :style="{fontSize: '42rpx', color: appColor}">{{prices.payPrice | moneyFormat}}</text>
					<text @click="show = true" style="font-size: 28rpx;color: #666;padding-left: 32rpx;">明细</text>
				</view>	
				<view class="good-detail-bootom-r">
					<view @click="save" :style="{backgroundColor: appColor}" class="ticket-item-title2-r">提交订单</view>
				</view>
			</view>	
		</view>
		<u-popup closeable :closeOnClickOverlay="false" :show="show" @close="close" :round="10">
			<view class="popup-title">价格明细</view>
			<scroll-view :scroll-y="true" style="height: 360rpx;">
				<view class="popup-title-cell">
					<view>
						<text>价格</text>
					</view>
					<view>
						<text style="padding-right: 128rpx;color: #999;">x{{value}}张</text>
						<text>&yen;{{ prices.totalPrice | moneyFormat }}</text>
					</view>
				</view>
				<view class="popup-title-cell">
					<view>
						<text>会员折扣</text>
					</view>
					<view>
						<text>-&yen;{{prices.discount | moneyFormat}}</text>
					</view>
				</view>
				<view class="popup-title-cell">
					<view>
						<text>优惠券</text>
					</view>
					<view>
						<text>-&yen;{{prices.couponPrice | moneyFormat}}</text>
					</view>
				</view>
				<view class="popup-title-cell">
					<view>
						<text>合计</text>
					</view>
					<view>
						<text :style="{color: appColor}">&yen;{{prices.payPrice | moneyFormat}}</text>
					</view>
				</view>
			</scroll-view>
		</u-popup>
	</view>
</template>

<script>
	import {mapState, mapActions} from 'vuex';
	import {computeOrderPrice, createOrder} from '@/api/home.js';
	import JoyPay from '@/components/joyPay'
	export default {
		components: {
			JoyPay
		},
		data() {
			return {
				show: false,
				value: 1,
				phone: '',
				model: {
					userinfo: {
						phone: ''
					}
				},
				prices: {
					payPrice: 0
				},
				pay: 1,
				list: []
			}
		},
		computed: {
			...mapState(['detail', 'userInfo', 'curCoupon']),
			appColor() {
				return this.appPrimaryColor || '#f40215'
			},
			scrollViewHeight() {
				return this.scrollHeight - 50 - 44 + 'px';
			}
		},
		watch: {
			curCoupon(val) {
				this.computeOrderPrice();
			},
		},
		onLoad() {
			this.setCurCoupon({curCoupon: {}});
			this.value = this.detail.play_number;
			this.model.userinfo.phone = this.userInfo.memberPhone;
			for (var i = 0; i < this.detail.play_number; i++) {
				this.list.push({
						userInfo: {
							name: '',
							card: ''
						},
					})
			}
		},
		methods: {
			...mapActions(['setCurCoupon']),
			changeCount({value}) {
				// 增加
				if(value > this.value) {
					this.list.push({
						userInfo: {
							name: '',
							card: ''
						},
					})
				// 减少	
				} else {
					this.list.pop();
				}
				this.value = value;
				this.$nextTick(() => {
					this.computeOrderPrice();	
				})
			},
			// 计算价格
			computeOrderPrice() {
				const that = this;
				const {id: couponId} = this.curCoupon;
				let buyCount = this.value;
				let postObj = {
					ticketId: this.detail.id,
					buyCount,
					couponId,
					ticketTime: this.detail.play_time
				}
				if(!couponId) {
					delete postObj.couponId
				}
				this.$cuLoading('加载中').then(() => {
					computeOrderPrice(postObj).then(res => {
						const {code, result, message} = res;
						uni.hideLoading();
						if(code === 5001) {
							uni.showModal({
								title: '提示',
								content: '优惠券不可用, 请重新选择',
								confirmColor: that.appColor,
								showCancel: false,
								success: function (res) {
									if (res.confirm) {
										that.setCurCoupon({curCoupon: {}});
										that.prices = res.result;
									}
								}
							})
						} else if(code === 200) {
							this.prices = res.result
						} else {
							this.$cuTip(message);
						}
					}).catch(() => {
						uni.hideLoading();
					})
				})
			},
			// 选择优惠券
			chooseCoupon() {
				let ticketId = this.detail.id;
				let buyCount = this.value;
				let couponId = this.curCoupon.id || '-1';
				let play_time = this.detail.play_time;
				let url = `/pages/me/chooseCoupon?couponId=${couponId}&ticketId=${ticketId}&buyCount=${buyCount}&way=2&time=${play_time}`
				this.$cuNavigateTo(url);
			},
			save() {
				let postObj = {
					buyCount: this.value,
					ticketTime: this.detail.play_time,
					ticketId: this.detail.id,
					phone: this.model.userinfo.phone,
					payMethod: this.pay,
					couponId: this.curCoupon.id
				};
				let lastI = false;
				for (let i = 0; i < this.list.length; i++) {
					let {userInfo} = this.list[i];
					if(this.list.length === 1) {
						let {name, card} = userInfo;
						name = uni.$u.trim(name);
						card = uni.$u.trim(card);
						if(!uni.$u.test.rangeLength(name, [2, 10])) {
							this.$cuTip('请输入姓名');
							break;
						}
						if(!uni.$u.test.idCard(card)) {
							this.$cuTip('请输入正确的身份证号');
							break;
						}
					} else {
						let {name, card} = userInfo;
						name = uni.$u.trim(name);
						card = uni.$u.trim(card);
						if(!uni.$u.test.rangeLength(name, [2, 10])) {
							this.$cuTip(`请输入游客${i+1}姓名`);
							break;
						}
						if(!uni.$u.test.idCard(card)) {
							this.$cuTip(`请输入游客${i+1}正确的身份证号`);
							break;
						}
					}
					lastI = (this.list.length - 1) === i;
				}
				if(!lastI) {
					return
				}
				let userInfo = [];
				for (let i = 0; i < this.list.length; i++) {
					userInfo.push({
						name: this.list[i].userInfo.name,
						cardNo: this.list[i].userInfo.card,
					})
				}
				postObj.userInfo = userInfo;
				this.$cuLoading('提交中').then(() => {
					createOrder(postObj).then(res => {
						const {success, result, message, code} = res;
						uni.hideLoading();
						if(success) {
							// 微信支付
							if(postObj.payMethod === 1) {
								const {orderId, wxPayResult: {nonceStr, packageValue, paySign, timeStamp, signType}} = result;
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp,
									nonceStr,
									package: packageValue,
									signType,
									paySign,
									success: function (res) {
										let url = '/pages/foster/paySuccess?id=' + result.orderId;
										uni.redirectTo({
											url
										})
									},
									fail: function (err) {
										console.log('fail:' + JSON.stringify(err));
									}
								})
							// 余额支付	
							} else if (postObj.payMethod === 2){
								let url = '/pages/foster/paySuccess?id=' + result.orderId;
								uni.redirectTo({
									url
								})
							}
						} else {
							if(code === 5001) {
								uni.showModal({
									title: '提示',
									content: '优惠券不可用, 请重新选择',
									confirmColor: that.appColor,
									showCancel: false,
									success: function (res) {
										if (res.confirm) {
											that.setCurCoupon({curCoupon: {}});
										}
									}
								})
							} else {
								this.$cuTip(message);
							}
						}
					}).catch(() => {
						uni.hideLoading();
					})
				})
				
			},
			close() {
				this.show = false
			  // console.log('close');
			},
			changePay(e) {
				this.pay = e;
			}
		}
	}
</script>


<style lang="scss" scoped>
	.shop-order-info-3-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx;
		.shop-order-info-3-item-l {
			font-size: 32rpx;
			line-height: 32rpx;
			color: #333;
		}
		.shop-order-info-3-item-r {
			font-size: 32rpx;
			line-height: 32rpx;
			color: #000;
		}
	}
	.popup-title {
		font-size: 32rpx;
		color: #333;
		text-align: center;
		padding: 32rpx 0;
	}
	.popup-title-cell {
		padding: 16rpx 32rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		color: #333;
		font-size: 28rpx;
	}
	.buy-notice1 {
		border-radius: 8rpx;
		font-size: 24rpx;
		padding: 8rpx 16rpx;
	}
	.popup-title1 {
		padding: 32rpx;
		display: flex;
		align-items: center;
	}
	.ticket-item-title2-r {
		padding: 16rpx 42rpx;
		font-size: 30rpx;
		color: #fff;
		border-radius: 4rpx;
	}
	.good-detail-bootom {
		background-color: #ffffff;
		position: fixed;
		height: 50px;
		width: 100vw;
		bottom: 0;
		left: 0;
		padding-bottom: constant(safe-area-inset-bottom);     /*兼容 iOS<11.2*/
		padding-bottom: env(safe-area-inset-bottom);  /*兼容 iOS>11.2*/
		box-sizing: content-box;
		.good-detail-bootom-l1 {
			display: flex;
			align-items: center;
		}
		.good-detail-bootom-r {
			text-align: right
		}
	}
</style>
